package net.lcheng.service.impl;

import com.alibaba.fastjson.JSON;
import net.lcheng.dao.*;
import net.lcheng.model.*;
import net.lcheng.service.ShoppingService;
import net.lcheng.utils.IdGenerator;
import net.lcheng.vo.OrderProductsEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * Created by LV on 2016/7/10.
 */
@Service("shoppingService")
public class ShoppingServiceImpl implements ShoppingService {
    @Resource
    private UserShoppingCartMapper shoppingCartMapper;
    @Resource
    private PProductMapper productMapper;
    @Resource
    private UserShippingAddressMapper addressMapper;
    @Resource
    private WxShopMapper shopMapper;
    @Resource
    private OOrderMapper orderMapper;
    @Resource
    private OOrderItemMapper orderItemMapper;
    @Resource
    private OOrderHistoryMapper orderHistoryMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private OOrderRefundMapper orderRefundMapper;
    /**
     * 添加购物车
     * @param cart（对象只用包含 shopId,userUserId,productId,productNum,productAttribute）
     * @return 添加成功返回1，失败返回0
     */
    @Override
    public int addGoodsToCart(UserShoppingCart cart) {
        //查找购物车中是否已经添加了该商品，添加了，增加数量
        if (cart!=null){
            UserShoppingCartExample example=new UserShoppingCartExample();
            example.createCriteria().andUserUserIdEqualTo(cart.getUserUserId())
                                    .andShopIdEqualTo(cart.getShopId())
                                    .andProductIdEqualTo(cart.getProductId())
                                    .andProductAttributeEqualTo(cart.getProductAttribute());
            List<UserShoppingCart> list=shoppingCartMapper.selectByExample(example);

            //如果存在，增加数量
            if (list!=null&&list.size()>0){
                UserShoppingCart shoppingCart=list.get(0);
                if (shoppingCart!=null) {
                    shoppingCart.setProductNum(shoppingCart.getProductNum()+cart.getProductNum());
                    shoppingCart.setModifyOn(new Date());
                    //更新数据库
                    int status = shoppingCartMapper.updateByPrimaryKeySelective(shoppingCart);
                    //添加购物车存在的商品成功返回2.失败返回0
                    if (status>0) return 2;
                    else return 0;
                }
                return 0;
            }else {//添加的商品不存在，添加一条
                PProduct product=productMapper.selectByPrimaryKey(cart.getProductId());
                if (product!=null){
                    UserShoppingCart shoppingCart=new UserShoppingCart();
                    shoppingCart.setCartId(UUID.randomUUID().toString());//主键
                    shoppingCart.setShopId(cart.getShopId());//商铺Id
                    shoppingCart.setUserUserId(cart.getUserUserId());//买家用户Id
                    shoppingCart.setProductId(product.getProductId());//商品ID
                    shoppingCart.setProductName(product.getProductName());
                    shoppingCart.setProductImage(product.getProductMainImage());
                    shoppingCart.setProductPrice(product.getSalePrice());
                    shoppingCart.setProductSku("");//商品SKU暂时为空，后期添加在加//Todo
                    shoppingCart.setProductAttribute(cart.getProductAttribute());//商品属性
                    shoppingCart.setProductNum(cart.getProductNum());//商品数量
                    shoppingCart.setCreateOn(new Date());
                    //添加到数据库
                    int status=shoppingCartMapper.insertSelective(shoppingCart);
                    //添加成功返回1.失败返回0
                    if (status>0) return 1;
                    else return 0;
                }
                return 0;
            }
        }
        return 0;
    }

    /**
     * 获取购物车的商品数量
     * @param shopId 店铺Id
     * @param buyerUserId 用户Id
     * @return
     */
    @Override
    public int getUserCartCount(int shopId, String buyerUserId) {
        UserShoppingCartExample example=new UserShoppingCartExample();
        example.createCriteria().andUserUserIdEqualTo(buyerUserId)
                .andShopIdEqualTo(shopId);
        return shoppingCartMapper.countByExample(example);
    }

    /**
     * 获取购物车里的所有商品
     * @param buyerUserId
     * @param shopId
     * @return
     */
    @Override
    public List<UserShoppingCart> getCartByUserIdAndShopId(String buyerUserId, int shopId) {
        UserShoppingCartExample example=new UserShoppingCartExample();
        example.createCriteria().andUserUserIdEqualTo(buyerUserId)
                .andShopIdEqualTo(shopId);
        return shoppingCartMapper.selectByExample(example);
    }

    /**
     * 主键查询购物车列表
     * @param key
     * @return
     */
    @Override
    public UserShoppingCart getCartByPrimaryKey(String key) {
        return shoppingCartMapper.selectByPrimaryKey(key);
    }

    /**
     * 删除购物车里记录
     * @param carts 购物车列表
     * @return
     */
    @Override
    public int deleteCartProduct(List<UserShoppingCart> carts) {
        if (carts!=null&&carts.size()>0){
            for(UserShoppingCart cart:carts){
                if (cart!=null){
                    shoppingCartMapper.deleteByPrimaryKey(cart.getCartId());
                }
            }
            return 1;
        }
        return 0;
    }

    /**
     * 商品结算
     * @param shopId 店铺Id
     * @param buyerUserId 买家UserId
     * @param carts 购物车商品列表
     * @return 返回订单的主键
     */
    @Transactional
    @Override
    public String settleAccount(int shopId, String buyerUserId, String addressId,List<UserShoppingCart> carts) {
        if(buyerUserId!=null&&addressId!=null){
            List<OOrderItem> orderItems=new ArrayList<>();//商品子表
            List<OrderProductsEntity> productsEntities=new ArrayList<>();//存放选择的商品对象，转换成json串的商品信息

            String orderId=UUID.randomUUID().toString();//提前生成主键，在添加商品子表时要用到

            double totalProductPrice=0;//产品总价
            double totalFreightPrice=0;//运费总价

            if (carts!=null&&carts.size()>0) {
                for (UserShoppingCart cart : carts) {

                    //查询每个商品的信息，确保信息的正确性
                    PProduct product = productMapper.selectByPrimaryKey(cart.getProductId());

                    if (product != null) {

                        totalProductPrice+=(cart.getProductPrice().doubleValue()*cart.getProductNum());//商品总价
                        totalFreightPrice+=(product.getFreight().doubleValue()*cart.getProductNum());//运费总价

                        //商品子表添加
                        OOrderItem orderItem = new OOrderItem();
                        orderItem.setItemId(UUID.randomUUID().toString());//主键
                        orderItem.setoOrderOrderId(orderId);//所属订单主键
                        orderItem.setProductId(product.getProductId());//商品主键
                        orderItem.setProductCode(product.getProductCode());
                        orderItem.setProductName(product.getProductName());
                        orderItem.setProductImage(product.getProductMainImage());
                        orderItem.setProductPrice(product.getSalePrice());
                        orderItem.setProductAttribute(cart.getProductAttribute());//商品属性
                        orderItem.setProductSku(cart.getProductSku());//商品编码信息
                        orderItem.setQuantity(cart.getProductNum());//商品数量
                        orderItem.setItemStatus(0);//商品状态
                        orderItem.setCreateOn(new Date());

                        orderItems.add(orderItem);//购物车选择的商品循环添加到商品子表List中

                        //转换对象添加
                        OrderProductsEntity productsEntity = new OrderProductsEntity();
                        productsEntity.setItemId(orderItem.getItemId());//商品子表ID
                        productsEntity.setId(product.getProductId());//商品Id
                        productsEntity.setCode(product.getProductCode());//商品code
                        productsEntity.setTitle(product.getProductName());//商品名字
                        productsEntity.setImage(product.getProductMainImage());//商品主图
                        productsEntity.setPrice(product.getSalePrice());//商品价格
                        productsEntity.setAttribute(cart.getProductAttribute());//商品属性
                        productsEntity.setQuantity(cart.getProductNum());//商品数量
                        productsEntity.setItemStatus(0);//商品状态

                        productsEntities.add(productsEntity);//循环添加到转换对象，以备json转换
                    }
                }

                //查询结算时添加的收获地址的信息
                UserShippingAddress address=addressMapper.selectByPrimaryKey(addressId);
                //查询店铺信息
                WxShop shop=shopMapper.selectByPrimaryKey(shopId);
                //买家信息
                User user=userMapper.selectByPrimaryKey(buyerUserId);

                if (address!=null&&shop!=null&&user!=null) {
                    //填充Order
                    OOrder order = new OOrder();
                    order.setOrderId(orderId);//主键
                    order.setOrderNum(IdGenerator.generateNumber());//Todo 订单编号暂时用8位
                    order.setBuyerUserId(user.getUserId());//买家userId
                    order.setBuyerUserPhone(user.getUserPhone());//买家userPhone
                    order.setBuyerUserName(user.getUserName());
                    order.setWxShopShopId(shop.getShopId());//店铺id
                    order.setSellerUserId(shop.getUserUserId());//店铺对应的用户Id
                    order.setSellerShopName(shop.getShopName());//店铺名
                    order.setOrderProducts(JSON.toJSONString(productsEntities));//订单商品列表json格式
                    order.setDiscountSummary("");//Todo 优惠说明暂时为空
                    order.setTotalProductAmount(new BigDecimal(totalProductPrice));//产品总价
                    order.setTotalFreightAmount(new BigDecimal(totalFreightPrice));//运费总价
                    order.setTotalDiscountAmount(new BigDecimal("0.0"));//优惠金额
                    order.setTotalOrderAmount(new BigDecimal(totalProductPrice + totalFreightPrice));//订单总价，有优惠金额，需要减去优惠金额
                    //Todo 积分和积分抵扣暂时为默认值
                    order.setPaymentMoneyAmount(new BigDecimal(totalProductPrice+totalFreightPrice));//实际支付金额
                    order.setPaymentStatus(0);//生成订单时，订单为未支付状态
                    order.setConsigneeName(address.getConsigneeName());//收货人姓名
                    order.setConsigneePhone(address.getConsigneePhone());//收货人电话
                    order.setProvinceCode(address.getProvinceCode());
                    order.setProvinceName(address.getProvinceName());
                    order.setCityName(address.getCityName());
                    order.setCityCode(address.getCityCode());
                    order.setDistrictCode(address.getDistrictCode());
                    order.setDistrictName(address.getDistrictName());
                    order.setAddress(address.getAddress());//收货人详细地址
                    order.setOrderTime(new Date());//下单时间
                    order.setOrderStatus(0);//订单状态

                    //生成订单
                    int status = orderMapper.insertSelective(order);
                    if (status > 0) {
                        //更新订单子表
                        for (OOrderItem orderItem : orderItems) {
                            //插入子商品列表
                            orderItemMapper.insert(orderItem);
                        }

                        //生成订单记录
                        OOrderHistory history = new OOrderHistory();
                        history.setHistoryId(UUID.randomUUID().toString());//主键
                        history.setOrderStatus(0);
                        history.setoOrderOrderId(orderId);
                        history.setComment("已下单");
                        history.setCreateOn(new Date());
                        history.setCreateBy(user.getUserName());
                        //添加订单记录
                        orderHistoryMapper.insertSelective(history);

                        return orderId;
                    }
                    return "";
                }
                return "";
            }
            return "";
        }
        return "";
    }

    /**
     * 退货退款（卖家已发货的情况下，暂时退货只能一个一个的退）
     * @param shopId 卖家商铺Id
     * @param buyerUserId 买家对应的UserId
     * @param orderId 订单Id
     * @param productId 退货的商品
     * @param attribute 退货商品的属性
     * @return
     */
    @Transactional
    @Override
    public int refundGoodsAndMoney(int shopId, String buyerUserId, String orderId, String productId, String attribute,int quantity,String reason) {
        if (buyerUserId!=null&&orderId!=null&&productId!=null) {
            //检查该商品是否具备申请退货条件（避免重复提交退货申请）
            OOrderItemExample example=new OOrderItemExample();
            example.createCriteria().andOOrderOrderIdEqualTo(orderId).andProductIdEqualTo(productId);
            List<OOrderItem> itemList=orderItemMapper.selectByExample(example);
            if (itemList!=null&&itemList.size()>0){
                OOrderItem orderItem=itemList.get(0);
                if (orderItem!=null){
                    int itemStatus=orderItem.getItemStatus();
                    //订单子商品状态
                    if (itemStatus==0){
                        //更新此商品为退货申请状态
                       OOrderItem item=new OOrderItem();
                        item.setItemId(orderItem.getItemId());
                        item.setItemStatus(1);
                        int changItemStatus=orderItemMapper.updateByPrimaryKeySelective(item);
                        if (changItemStatus>0){
                            //获取商铺信息
                            WxShop wxShop = shopMapper.selectByPrimaryKey(shopId);
                            //获取用户信息
                            User user = userMapper.selectByPrimaryKey(buyerUserId);
                            //获取产品信息
                            PProduct product = productMapper.selectByPrimaryKey(productId);
                            //原订单信息
                            OOrder order=orderMapper.selectByPrimaryKey(orderId);

                            if(product!=null&&order!=null&&user!=null&&wxShop!=null){
                                //将退货的商品名称、图片等属性转换成约定的json格式
                                OrderProductsEntity entity=new OrderProductsEntity();
                                entity.setId(product.getProductId());//商品id
                                entity.setTitle(product.getProductName());//商品名称
                                entity.setPrice(product.getSalePrice());//商品价格
                                entity.setCode(product.getProductCode());//商品编号
                                entity.setImage(product.getProductMainImage());//商品图片
                                entity.setAttribute(attribute);//商品属性
                                entity.setQuantity(quantity);//商品个数
                                entity.setItemStatus(1);//退货的商品状态为退货申请中

                                OOrderRefund orderRefund=new OOrderRefund();
                                orderRefund.setOrderRefundId(UUID.randomUUID().toString());//主键
                                orderRefund.setOrderRefundNum(IdGenerator.generateNumber());//Todo 货订单编号暂时8位
                                orderRefund.setOrderId(order.getOrderId());//原订单id
                                orderRefund.setOrderNum(order.getOrderNum());//原订单编号
                                orderRefund.setBuyerUserId(user.getUserId());//买家对应userId
                                orderRefund.setBuyerUserName(user.getUserName());//买家姓名
                                orderRefund.setBuyerUserPhone(user.getUserPhone());//买家手机号
                                orderRefund.setWxShopShopId(wxShop.getShopId());//店铺Id
                                orderRefund.setSellerUserId(wxShop.getUserUserId());//卖家UserId
                                orderRefund.setSellerShopName(wxShop.getShopName());//店铺名
                                orderRefund.setOrderProducts(JSON.toJSONString(entity));//要退的商品转换成约定的json格式
                                orderRefund.setTotalProductAmount(new BigDecimal(product.getSalePrice().doubleValue()*quantity));//商品总价(微店价*个数) TODO
                                orderRefund.setTotalDiscountAmount(new BigDecimal("0.0"));//优惠金额默认为0
                                orderRefund.setTotalOrderAmount(orderRefund.getTotalProductAmount());//订单总价默认为产品总价
                                orderRefund.setTotalFreightAmount(order.getTotalFreightAmount());//运费金额为原订单的运费金额
                                orderRefund.setPaymentMoneyAmount(orderRefund.getTotalProductAmount());//要退的订单实际支付的金额为商品总价
                                orderRefund.setRefundReason(reason);//退款退货原因
                                orderRefund.setPaymentStatus(0);//退款状态初始化为未支付状态
                                orderRefund.setGoodsStatus(0);//申请退货时，货物状态为等待买家发货
                                orderRefund.setOrderStatus(0);//退货订单状态
                                orderRefund.setOrderTime(new Date());//退货订单发起时间

                                int status=orderRefundMapper.insert(orderRefund);

                                if (status>0){
                                    //添加订单日志
                                    OOrderHistory history=new OOrderHistory();
                                    history.setHistoryId(UUID.randomUUID().toString());//主键
                                    history.setoOrderOrderId(order.getOrderId());//订单
                                    history.setOrderStatus(order.getOrderStatus());//订单状态
                                    history.setComment("发起退货退款申请");
                                    history.setCreateOn(new Date());
                                    history.setCreateBy(order.getBuyerUserName());

                                    int hStatus=orderHistoryMapper.insertSelective(history);

                                    if (hStatus>0) return 1;

                                    else return 0;
                                }
                                return 0;
                             }
                            return 0;
                        }
                        return 0;
                    }
                    return 0;
                }
                return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 退货退款（卖家已发货的情况下，暂时退货只能一个一个的退）
     * @param itemId 要退的订单子商品主键
     * @param reason 退单理由
     * @param cause 退单原因
     * @return int
     */
    @Transactional
    @Override
    public int refundGoodsAndMoney(String itemId, String reason, String cause) {
        if (itemId!=null&&!itemId.equals("")) {
            //获取订单子商品的信息
            OOrderItem orderItem=orderItemMapper.selectByPrimaryKey(itemId);

            //检查该商品是否具备申请退货条件（避免重复提交退货申请）
            if (orderItem!=null&&orderItem.getItemStatus()==0){
                //更新此商品为退货申请状态
                OOrderItem item=new OOrderItem();
                item.setItemId(orderItem.getItemId());
                item.setItemStatus(1);
                int changItemStatus=orderItemMapper.updateByPrimaryKeySelective(item);

                //状态改变生效
                if (changItemStatus>0){
                    //原订单信息
                    OOrder order=orderMapper.selectByPrimaryKey(orderItem.getoOrderOrderId());

                    if (order!=null){
                    //获取商铺信息
                    WxShop wxShop = shopMapper.selectByPrimaryKey(order.getWxShopShopId());
                    //获取用户信息
                    User user = userMapper.selectByPrimaryKey(order.getBuyerUserId());
                    //获取产品信息
                    PProduct product = productMapper.selectByPrimaryKey(orderItem.getProductId());

                    //更新原订单的子商品的Json串
                        List<OrderProductsEntity> entities=JSON.parseArray(order.getOrderProducts(),OrderProductsEntity.class);
                        for (OrderProductsEntity entity:entities){
                            if (entity.getItemId().equals(itemId)){
                                entity.setItemStatus(1);
                            }
                        }
                        order.setOrderProducts(JSON.toJSONString(entities));
                        int orderStatus=orderMapper.updateByPrimaryKey(order);

                            if (orderStatus>0){
                                if(product!=null&&user!=null&&wxShop!=null) {
                                    //将退货的商品名称、图片等属性转换成约定的json格式
                                    OrderProductsEntity entity = new OrderProductsEntity();
                                    entity.setItemId(orderItem.getItemId());//商品子商品主键
                                    entity.setId(product.getProductId());//商品id
                                    entity.setTitle(product.getProductName());//商品名称
                                    entity.setPrice(product.getSalePrice());//商品价格
                                    entity.setCode(product.getProductCode());//商品编号
                                    entity.setImage(product.getProductMainImage());//商品图片
                                    entity.setAttribute(orderItem.getProductAttribute());//商品属性
                                    entity.setQuantity(orderItem.getQuantity());//商品个数
                                    entity.setItemStatus(1);//退货的商品状态为退货申请中
                                    //在解析的时候，是解析成list,所以换成list
                                    List<OrderProductsEntity> list=new ArrayList<>();
                                    list.add(entity);

                                    OOrderRefund orderRefund = new OOrderRefund();
                                    orderRefund.setOrderRefundId(UUID.randomUUID().toString());//主键
                                    orderRefund.setOrderRefundNum(IdGenerator.generateNumber());//Todo 货订单编号暂时8位
                                    orderRefund.setOrderId(order.getOrderId());//原订单id
                                    orderRefund.setOrderNum(order.getOrderNum());//原订单编号
                                    orderRefund.setBuyerUserId(user.getUserId());//买家对应userId
                                    orderRefund.setBuyerUserName(user.getUserName());//买家姓名
                                    orderRefund.setBuyerUserPhone(user.getUserPhone());//买家手机号
                                    orderRefund.setWxShopShopId(wxShop.getShopId());//店铺Id
                                    orderRefund.setSellerUserId(wxShop.getUserUserId());//卖家UserId
                                    orderRefund.setSellerShopName(wxShop.getShopName());//店铺名
                                    orderRefund.setOrderProducts(JSON.toJSONString(list));//要退的商品转换成约定的json格式
                                    orderRefund.setTotalProductAmount(new BigDecimal(product.getSalePrice().doubleValue() * orderItem.getQuantity()));//商品总价(微店价*个数) TODO
                                    orderRefund.setTotalDiscountAmount(new BigDecimal("0.0"));//优惠金额默认为0
                                    orderRefund.setTotalOrderAmount(orderRefund.getTotalProductAmount());//订单总价默认为产品总价
                                    orderRefund.setTotalFreightAmount(order.getTotalFreightAmount());//运费金额为原订单的运费金额
                                    orderRefund.setPaymentMoneyAmount(orderRefund.getTotalProductAmount());//要退的订单实际支付的金额为商品总价
                                    orderRefund.setRefundReason(reason);//退款退货理由
                                    orderRefund.setRefundCause(cause);//退款退货原因
                                    orderRefund.setPaymentStatus(0);//退款状态初始化为未支付状态
                                    orderRefund.setGoodsStatus(1);//申请退货时，货物状态为卖家已发货
                                    orderRefund.setOrderStatus(0);//退货订单状态
                                    orderRefund.setOrderTime(new Date());//退货订单发起时间

                                    int status = orderRefundMapper.insert(orderRefund);

                                    if (status > 0) {
                                        //添加订单日志
                                        OOrderHistory history = new OOrderHistory();
                                        history.setHistoryId(UUID.randomUUID().toString());//主键
                                        history.setoOrderOrderId(order.getOrderId());//订单
                                        history.setOrderStatus(order.getOrderStatus());//订单状态
                                        history.setComment("发起退货退款申请");
                                        history.setCreateOn(new Date());
                                        history.setCreateBy(order.getBuyerUserName());

                                        int hStatus = orderHistoryMapper.insertSelective(history);

                                        if (hStatus > 0) return 1;

                                        else return 0;
                                    }
                                    return 0;
                                }
                                return 0;
                            }
                            return 0;
                        }
                        return 0;
                    }
                    return 0;
                }
                return 0;
            }
            return 0;
    }

    /**
     * 申请退款（卖家没有发货的情况）
     * @param shopId 商铺Id
     * @param buyerUserId 买家对应的UserId
     * @param orderId 原订单Id
     * @return int
     */
    @Transactional
    @Override
    public int refundMoney(int shopId, String buyerUserId, String orderId,String reason) {
        //
        if (buyerUserId!=null&&orderId!=null){
            //检查申请退款订单已经生成（避免退款订单生成多个）
            OOrderRefundExample example=new OOrderRefundExample();
            example.createCriteria().andOrderIdEqualTo(orderId);
            List<OOrderRefund> list=orderRefundMapper.selectByExample(example);
            //如果没有生成才会生成退货订单
            if (list!=null&&list.size()==0){
                //获取商铺信息
                WxShop wxShop = shopMapper.selectByPrimaryKey(shopId);
                //买家信息
                User user = userMapper.selectByPrimaryKey(buyerUserId);
                //原订单信息
                OOrder order=orderMapper.selectByPrimaryKey(orderId);

                if (user!=null&&order!=null){
                    OOrderRefund orderRefund=new OOrderRefund();
                    orderRefund.setOrderRefundId(UUID.randomUUID().toString());//主键
                    orderRefund.setOrderRefundNum(IdGenerator.generateNumber());//Todo 货订单编号暂时8位
                    orderRefund.setOrderId(order.getOrderId());//原订单id
                    orderRefund.setOrderNum(order.getOrderNum());//原订单编号
                    orderRefund.setBuyerUserId(user.getUserId());//买家对应userId
                    orderRefund.setBuyerUserName(user.getUserName());//买家姓名
                    orderRefund.setBuyerUserPhone(user.getUserPhone());//买家手机号
                    orderRefund.setWxShopShopId(wxShop.getShopId());//店铺Id
                    orderRefund.setSellerUserId(wxShop.getUserUserId());//卖家UserId
                    orderRefund.setSellerShopName(wxShop.getShopName());//店铺名
                    orderRefund.setDiscountSummary(order.getDiscountSummary());//优惠说明，直接复制原订单的
                    orderRefund.setOrderProducts(order.getOrderProducts());//直接将原订单货物复制过来
                    orderRefund.setTotalProductAmount(order.getTotalProductAmount());//直接复制
                    orderRefund.setTotalDiscountAmount(order.getTotalDiscountAmount());//直接复制
                    orderRefund.setTotalOrderAmount(order.getTotalOrderAmount());//直接复制订单的
                    orderRefund.setTotalFreightAmount(order.getTotalFreightAmount());//运费金额为原订单的运费金额
                    orderRefund.setPaymentMoneyAmount(orderRefund.getTotalProductAmount());//要退的订单实际支付的金额为商品总价
                    orderRefund.setRefundReason(reason);//退款退货原因
                    orderRefund.setPaymentStatus(0);//退款状态初始化为未支付状态
                    orderRefund.setGoodsStatus(-1);//申请退货时，货物状态为卖家未发货
                    orderRefund.setOrderStatus(0);//退货订单状态
                    orderRefund.setOrderTime(new Date());//退货订单发起时间

                    int status=orderRefundMapper.insert(orderRefund);

                    if (status>0){
                        //添加订单日志
                        OOrderHistory history=new OOrderHistory();
                        history.setHistoryId(UUID.randomUUID().toString());//主键
                        history.setoOrderOrderId(order.getOrderId());//订单
                        history.setOrderStatus(order.getOrderStatus());//订单状态
                        history.setComment("发起退款申请");
                        history.setCreateOn(new Date());
                        history.setCreateBy(order.getBuyerUserName());

                        int hStatus=orderHistoryMapper.insertSelective(history);

                        if (hStatus>0) return 1;

                        else return 0;
                    }
                    return 0;
                }
                return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 申请退款（卖家没有发货的情况）
     * @param orderId 申请退款的订单Id
     * @param reason  退单理由
     * @param cause 退单原因
     * @return int
     */
    @Transactional
    @Override
    public int refundMoney(String orderId, String reason, String cause) {
        if (orderId!=null&&!orderId.equals("")){
            //检查申请退款订单已经生成（避免退款订单生成多个）
            OOrderRefundExample example=new OOrderRefundExample();
            example.createCriteria().andOrderIdEqualTo(orderId);
            List<OOrderRefund> list=orderRefundMapper.selectByExample(example);

            //如果没有生成才会生成退货订单
            if (list!=null&&list.size()==0){
                //获取订单信息
                OOrder order=orderMapper.selectByPrimaryKey(orderId);
                if (order!=null){
                //获取商铺信息
                WxShop wxShop = shopMapper.selectByPrimaryKey(order.getWxShopShopId());
                //买家信息
                User user = userMapper.selectByPrimaryKey(order.getBuyerUserId());

                    if (user!=null) {
                        OOrderRefund orderRefund = new OOrderRefund();
                        orderRefund.setOrderRefundId(UUID.randomUUID().toString());//主键
                        orderRefund.setOrderRefundNum(IdGenerator.generateNumber());//Todo 货订单编号暂时8位
                        orderRefund.setOrderId(order.getOrderId());//原订单id
                        orderRefund.setOrderNum(order.getOrderNum());//原订单编号
                        orderRefund.setBuyerUserId(user.getUserId());//买家对应userId
                        orderRefund.setBuyerUserName(user.getUserName());//买家姓名
                        orderRefund.setBuyerUserPhone(user.getUserPhone());//买家手机号
                        orderRefund.setWxShopShopId(wxShop.getShopId());//店铺Id
                        orderRefund.setSellerUserId(wxShop.getUserUserId());//卖家UserId
                        orderRefund.setSellerShopName(wxShop.getShopName());//店铺名
                        orderRefund.setDiscountSummary(order.getDiscountSummary());//优惠说明，直接复制原订单的
                        orderRefund.setOrderProducts(order.getOrderProducts());//直接将原订单货物复制过来
                        orderRefund.setTotalProductAmount(order.getTotalProductAmount());//直接复制
                        orderRefund.setTotalDiscountAmount(order.getTotalDiscountAmount());//直接复制
                        orderRefund.setTotalOrderAmount(order.getTotalOrderAmount());//直接复制订单的
                        orderRefund.setTotalFreightAmount(order.getTotalFreightAmount());//运费金额为原订单的运费金额
                        orderRefund.setPaymentMoneyAmount(orderRefund.getTotalProductAmount());//要退的订单实际支付的金额为商品总价
                        orderRefund.setRefundReason(reason);//退款退货理由
                        orderRefund.setRefundCause(cause);//退款原因
                        orderRefund.setPaymentStatus(0);//退款状态初始化为未支付状态
                        orderRefund.setGoodsStatus(-1);//申请退货时，货物状态为卖家未发货
                        orderRefund.setOrderStatus(0);//退货订单状态
                        orderRefund.setOrderTime(new Date());//退货订单发起时间

                        int status = orderRefundMapper.insert(orderRefund);

                        if (status > 0) {
                            //添加订单日志
                            OOrderHistory history = new OOrderHistory();
                            history.setHistoryId(UUID.randomUUID().toString());//主键
                            history.setoOrderOrderId(order.getOrderId());//订单
                            history.setOrderStatus(order.getOrderStatus());//订单状态
                            history.setComment("发起退款申请");
                            history.setCreateOn(new Date());
                            history.setCreateBy(order.getBuyerUserName());

                            int historyStatus = orderHistoryMapper.insertSelective(history);

                            if (historyStatus > 0) return 1;

                            else return 0;
                        }
                    return 0;
                    }
                    return 0;
                }
                return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 买家发货
     * @param RefundId 退货订单Id
     * @param shippingCode 物流公司代码
     * @param shippingName 物流公司名
     * @param trackingNum 快递单号
     * @return int
     */
    @Transactional
    @Override
    public int deliverGoodsByBuyer(String RefundId, String shippingCode, String shippingName, String trackingNum) {
        OOrderRefund orderRefund=new OOrderRefund();
        orderRefund.setOrderRefundId(RefundId);
        orderRefund.setShippingCompanyCode(shippingCode);
        orderRefund.setShippingCompanyName(shippingName);
        orderRefund.setShippingTrackingNumber(trackingNum);//订单号
        orderRefund.setOrderStatus(2);//订单状态变为买家已发货
        orderRefund.setGoodsStatus(1);//货物状态为买家已发出
        orderRefund.setShippingTime(new Date());//买家发货时间

        int status=orderRefundMapper.updateByPrimaryKeySelective(orderRefund);

        if (status>0){
            OOrderRefund orderRefund1=orderRefundMapper.selectByPrimaryKey(RefundId);
            if (orderRefund1!=null) {
                //添加订单记录日志
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());//主键
                history.setoOrderOrderId(orderRefund1.getOrderId());//原订单ID
                history.setComment("买家已将货物发出，等待卖家收货");
                history.setOrderStatus(3);
                history.setCreateBy(orderRefund1.getBuyerUserName());
                history.setCreateOn(new Date());

                orderHistoryMapper.insertSelective(history);

                return 1;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 卖家发货及取消退款订单
     * @param refundId 退单Id
     * @param shippingCode 快递公司代码
     * @param shippingName 快递公司名
     * @param trackingNum 快递号
     * @return int
     */
    @Transactional
    @Override
    public int deliverGoodsThenCancelRefundOrder(String refundId, String shippingCode, String shippingName, String trackingNum) {
        //获取退款订单信息
        OOrderRefund orderRefund=orderRefundMapper.selectByPrimaryKey(refundId);

        if (orderRefund!=null) {
            //获取原订单信息
            OOrder order=orderMapper.selectByPrimaryKey(orderRefund.getOrderId());

            if (order!=null) {
                //给原订单更新快递信息更改订单状态为已发货状态
                OOrder order1 = new OOrder();
                order1.setOrderId(order.getOrderId());//主键
                order1.setShippingCompanyName(shippingName);
                order1.setShippingCompanyCode(shippingCode);
                order1.setShippingTrackingNumber(trackingNum);//快递号
                order1.setShippingTime(new Date());
                order1.setOrderStatus(2);//订单状态改变为订单已发货

                int status = orderMapper.updateByPrimaryKeySelective(order1);

                if (status > 0) {
                    //更新退货订单信息
                    OOrderRefund orderRefund1=new OOrderRefund();
                    orderRefund1.setOrderRefundId(orderRefund.getOrderRefundId());//主键
                    orderRefund1.setOrderStatus(-1);//退货订单状态为已取消
                    orderRefund1.setOrderCancelDescription("卖家主动取消");
                    orderRefund1.setModifyOn(new Date());

                    int status1=orderRefundMapper.updateByPrimaryKeySelective(orderRefund1);

                    if (status1>0) {
                        //添加订单日志信息
                        OOrderHistory history = new OOrderHistory();
                        history.setHistoryId(UUID.randomUUID().toString());
                        history.setComment("卖家取消退款申请，卖家已发货");
                        history.setoOrderOrderId(order.getOrderId());
                        history.setOrderStatus(2);
                        history.setCreateOn(new Date());
                        history.setCreateBy(order.getSellerShopName());
                        int hStatus = orderHistoryMapper.insertSelective(history);

                        if (hStatus>0)
                            return 1;
                        else
                            return 0;
                    }
                    return 0;
                }
                return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 卖家同意退货退款
     * @param orderRefund 此对象已经包含卖家填写的货物退的地址和要要退的金额（还需添加收货人地址和姓名）
     * @return int
     */
    @Transactional
    @Override
    public int agreeRefundMoneyAndGoods(OOrderRefund orderRefund) {
        if (orderRefund!=null){
            //填写收货人的姓名和联系方式
            //获取卖家信息
            User user=userMapper.selectByPrimaryKey(orderRefund.getSellerUserId());
            orderRefund.setConsigneeName(user.getUserName());
            orderRefund.setConsigneePhone(user.getUserPhone());
            //订单的状态变为等待买家发货
            orderRefund.setOrderStatus(1);

            int status=orderRefundMapper.updateByPrimaryKeySelective(orderRefund);
            if (status>0){
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());
                history.setComment("卖家通过申请，等待买家发货");
                history.setoOrderOrderId(orderRefund.getOrderId());
                history.setOrderStatus(2);
                history.setCreateOn(new Date());
                history.setCreateBy(orderRefund.getSellerShopName());
                int hStatus = orderHistoryMapper.insertSelective(history);

                if (hStatus>0)
                    return 1;
                else
                    return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 买家退回货物
     * @param orderRefund (包含快递信息)
     * @return int
     */
    @Transactional
    @Override
    public int refundGoodsByUser(OOrderRefund orderRefund) {
        if (orderRefund!=null){
            //更改退单状态
            orderRefund.setOrderStatus(2);//买家已发货
            orderRefund.setShippingTime(new Date());//买家发货时间

            //更新订单状态
            int status=orderRefundMapper.updateByPrimaryKeySelective(orderRefund);
            if (status>0){
                //添加订单日志信息
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());
                history.setComment("买家已发货，等待卖家确认");
                history.setoOrderOrderId(orderRefund.getOrderId());
                history.setOrderStatus(2);
                history.setCreateOn(new Date());
                history.setCreateBy(orderRefund.getBuyerUserName());
                int hStatus = orderHistoryMapper.insertSelective(history);
                if (hStatus>0)
                    return 1;
                else return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 买家确认收货
     * @param order 收货的订单
     * @return int
     */
    @Transactional
    @Override
    public int confirmReceiveGoods(OOrder order) {
        if (order!=null){
            int status=orderMapper.updateByPrimaryKeySelective(order);

            if (status>0){
             //生成订单信息
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());
                history.setComment("买家已发货，等待卖家确认");
                history.setoOrderOrderId(order.getOrderId());
                history.setOrderStatus(3);
                history.setCreateOn(new Date());
                history.setCreateBy(order.getBuyerUserName());
                int hStatus = orderHistoryMapper.insertSelective(history);
                if (hStatus>0)
                    return 1;
                else return 0;
            }
            return 0;
        }
        return 0;
    }

    /**
     * 买家支付订单
     * @param order 要支付的订单
     * @return int
     */
    @Transactional
    @Override
    public int paymentByBuyer(OOrder order) {
        if (order!=null){
            //更新支付信息
            int status=orderMapper.updateByPrimaryKeySelective(order);

            if (status>0){
                //添加订单日志信息
                OOrderHistory history = new OOrderHistory();
                history.setHistoryId(UUID.randomUUID().toString());
                history.setComment("买家已付款，等待发货");
                history.setoOrderOrderId(order.getOrderId());
                history.setOrderStatus(1);
                history.setCreateOn(new Date());
                history.setCreateBy(order.getBuyerUserName());
                int hStatus = orderHistoryMapper.insertSelective(history);

                if (hStatus>0)
                    return 1;
                else
                    return 0;
            }
            return 0;
        }
        return 0;
    }
}
